package com.doodle.common.utils;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

public abstract class FeedMoreLoader<T, V> extends AsyncDataLoader<V> {
	
	public static class FeedMoreResult<T> {
		public List<T> mData = new ArrayList<T>();
		public int mTotalCount = 0;
		public int mResultCount = 0;
	}
	
	private final int mRequestCount;
	
	protected List<T> mData;
	protected V mReturnedResult;
	
	protected int mOffset = 0;
	
	protected int mTotalCount;
	protected boolean mIsFinished = true;
	protected boolean mNeedFeedMore;
	protected boolean mIsLoading = false;
	
	public FeedMoreLoader(Context context, int requestCount) {
		super(context);
		mRequestCount = requestCount;
	}
	
	public void feedMore() {
		if (!mIsFinished) {
			forceLoad();
		}
	}
	
	public boolean isLoading() {
		return mIsLoading;
	}
	
	public boolean isFinished() {
		return mIsFinished;
	}

	@Override
	public V loadInBackground() {
		mIsLoading = true;
		FeedMoreResult<T> result = doFeedMore(mOffset, mRequestCount);
		
		if (result != null) {
			int dataCount = result.mData == null ? 0 : result.mData.size();
			if (mData == null) {
				mData = new ArrayList<T>(dataCount);
			}
			if (dataCount > 0) {
				mData.addAll(result.mData);
			}
			
			mOffset += result.mResultCount;
			mTotalCount = result.mTotalCount;
			
			if (mTotalCount >= 0) {
				mIsFinished = mOffset >= mTotalCount;
			} else {
				mIsFinished = result.mData.size() < mRequestCount;
			}
			
			if (mData != null) {
				mReturnedResult = getComposedResult(mData);
			} else {
				mReturnedResult = null;
			}
		}
		mIsLoading = false;
		return mReturnedResult;
	}
	
	public void clear() {
		if (mData != null) {
			mData.clear();
		}
		mTotalCount = 0;
		mReturnedResult = null;
		mOffset = 0;
		mIsFinished = false;
		mNeedFeedMore = false;
	}
	
	/**
	 * 构造结果返回的数据
	 * @param data 不为空
	 * @return
	 */
	protected abstract V getComposedResult(List<T> data);
	protected abstract FeedMoreResult<T> doFeedMore(int offset, int count);
}
